package com.klm.netty;

import com.klm.config.NettyConfig;
import com.klm.netty.codec.MessageTypeRegistry;
import com.klm.netty.handler.TranslateMessageHandler;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;

/**
 * @author wq
 */
@Slf4j
@Component
public class NettyServer {
    private final NettyConfig nettyConfig;
    private final MessageTypeRegistry messageTypeRegistry;
    private final TranslateMessageHandler messageHandler;
    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;
    private ChannelFuture channelFuture;

    public NettyServer(NettyConfig nettyConfig, 
                      MessageTypeRegistry messageTypeRegistry,
                      TranslateMessageHandler messageHandler) {
        this.nettyConfig = nettyConfig;
        this.messageTypeRegistry = messageTypeRegistry;
        this.messageHandler = messageHandler;
    }

    @PostConstruct
    public void start() {
//        if (!nettyConfig.isEnabled()) {
//            log.info("Netty server is disabled");
//            return;
//        }
//
//        bossGroup = new NioEventLoopGroup(1);
//        workerGroup = new NioEventLoopGroup(nettyConfig.getWorkerThreads());
//
//        try {
//            ServerBootstrap bootstrap = new ServerBootstrap();
//            bootstrap.group(bossGroup, workerGroup)
//                    .channel(NioServerSocketChannel.class)
//                    .option(ChannelOption.SO_BACKLOG, nettyConfig.getMaxConnections())
//                    .childOption(ChannelOption.SO_KEEPALIVE, true)
//                    .childOption(ChannelOption.TCP_NODELAY, true)
//                    .childHandler(new ChannelInitializer<SocketChannel>() {
//                        @Override
//                        protected void initChannel(SocketChannel ch) {
//                            ch.pipeline()
//                                    .addLast(new IdleStateHandler(
//                                            nettyConfig.getReadTimeout(),
//                                            nettyConfig.getWriteTimeout(),
//                                            0,
//                                            TimeUnit.MILLISECONDS))
//                                    .addLast(new ProtobufEncoder())
//                                    .addLast(new ProtobufDecoder(messageTypeRegistry.getPrototype(1))) // 使用第一个消息类型作为默认解码器
//                                    .addLast(messageHandler);
//                        }
//                    });
//
//            channelFuture = bootstrap.bind(nettyConfig.getHost(), nettyConfig.getPort()).sync();
//            log.info("Netty server started on {}:{}", nettyConfig.getHost(), nettyConfig.getPort());
//        } catch (Exception e) {
//            log.error("Failed to start Netty server", e);
//            shutdown();
//        }
    }

    @PreDestroy
    public void shutdown() {
        if (channelFuture != null) {
            channelFuture.channel().close();
        }
        if (bossGroup != null) {
            bossGroup.shutdownGracefully();
        }
        if (workerGroup != null) {
            workerGroup.shutdownGracefully();
        }
        log.info("Netty server shutdown completed");
    }
} 